package edu.tum.cs.stageflow.executionframework;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.ArrayBlockingQueue;

public class Flow<T> extends ArrayBlockingQueue<T> {
	private static final String FLOWCAPACITY = "flowcapacity";
	private static final String FLOWPROPERY_FILE = "flow.properties";
	private boolean isFinished = false;

	public Flow() {
		this(getFlowCapacity());
	}

	public Flow(int capacity) {
		super(capacity);
	}

	public boolean isFinished() {
		return isFinished;
	}

	public void setFinished(boolean isFinished) {
		this.isFinished = isFinished;
	}

	@Override
	public void put(T e) throws InterruptedException {
		try {
			synchronized (this) {
				while (!this.offer(e)) {
					this.wait();
				}
				this.notifyAll();
			}
		} catch (InterruptedException ie) {
			ie.printStackTrace();
		}
	};

	// load flow capacity from config file
	private static int getFlowCapacity() {
		Properties prop = new Properties();
		InputStream input = null;
		int flowCap = 50;

		try {
			input = new FileInputStream(FLOWPROPERY_FILE);
			prop.load(input);
			flowCap = Integer.parseInt(prop.getProperty(FLOWCAPACITY));
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return flowCap;
	}
}
